//
//  WPMedicalRecordsVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/12.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPMedicalRecordsVC.h"
#import "WPMRTableViewCell.h"
#import "WPMRModel.h"
#import "WPBaseNavigationController.h"
#import "WPHomeViewController.h"
#import "WPUpdateDataVC.h"
#import "WPMineLoginVC.h"
#import "WPNewEditeSpecificCasesVC.h"
#import "WPShareToCommonCaseVC.h"

@interface WPMedicalRecordsVC ()<UITableViewDataSource,UITableViewDelegate,WPShareToCommonCaseVCDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *addMRBtn;
@property (nonatomic,strong)UIImageView *guideImageView;
@property(nonatomic,strong)NSMutableArray *models;
@property(nonatomic,assign)NSInteger pageIndex;

@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UIAlertView *alertView1;
@property(nonatomic,strong)WPMRModel *cancelModel;
@property(nonatomic, strong)NSIndexPath *cancelIndexPath;

@end

static NSString *ID = @"mrCell";
static NSString *url = @"record/findRecordByUserId.do";

@implementation WPMedicalRecordsVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //        第一次使用
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:isFirst_Case] && self.models.count == 1)
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirst_Case];
        
        //        判断是不是第一次使用
        NSString *name = nil;
        if (SCREEN_WIDTH < 375)
        {
            name = @"case_first_using5";
        }
        else if (SCREEN_WIDTH < 414)
        {
            name = @"case_first_using6";
        }
        else
        {
            name = @"case_first_using6p";
        }
        UIImageView *guideImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
        self.imageView = guideImageView;
        guideImageView.userInteractionEnabled = YES;
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:guideImageView];
        
        [guideImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(keyWindow);
        }];
        
        UITapGestureRecognizer *TGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideImageViewDidClick:)];
        [guideImageView addGestureRecognizer:TGR];
    }
}

-(void)guideImageViewDidClick:(UITapGestureRecognizer *)tgr
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:isFirst_Case2])
    {
        [self.imageView removeFromSuperview];
    }
    else
    {
        NSString *name = nil;
        if (SCREEN_WIDTH < 375)
        {
            name = @"case2_first_using5";
        }
        else if (SCREEN_WIDTH < 414)
        {
            name = @"case2_first_using6";
        }
        else
        {
            name = @"case2_first_using6p";
        }
        self.imageView.image = [UIImage imageNamed:name];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirst_Case2];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.addMRBtn.hidden = self.isHidden;
    
    self.pageIndex = 1;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    
    self.tableView.estimatedRowHeight = 20;
    [self.tableView registerClass:[WPMRTableViewCell class] forCellReuseIdentifier:ID];

    
    /* 配置下拉刷新控件 */
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//      刷新数据
        [weakSelf refreshData];
        
    }];
    self.tableView.mj_header = mj_header;
    [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    mj_header.stateLabel.textColor = GLobalFontColor;
    mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
//    上啦刷新控件
    //    上拉刷新控件
    MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [weakSelf loadMoreData];
        [weakSelf.tableView.mj_footer endRefreshing];
        
    }];
    self.tableView.mj_footer = mj_footer;
    mj_footer.automaticallyRefresh = NO;
    mj_footer.automaticallyHidden = NO;
    
    //    加载数据
    [self loadData];
}

-(NSMutableArray *)models
{
    if (_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}

-(void)loadData
{
    [self showWithStatus:@"正在加载"];
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        
        if([responseDic[@"result"] isEqualToString:@"success"])
        {
            NSArray *detailArr = responseDic[@"detail"];
            if ([detailArr count])
            {
                self.tableView.hidden = NO;
                
                for (NSDictionary  *obj in detailArr)
                {
                    WPMRModel *model = [WPMRModel yy_modelWithDictionary:obj];
                    [self.models addObject:model];
                    //  保存起来
                    //  [NSKeyedArchiver archiveRootObject:self.models toFile:MRFilePath];
                    NSLog(@"***%@",obj);
                }
                if (self.models.count < 10)
                {
                    self.tableView.mj_footer.hidden = YES;
                }
                else
                {
                    self.tableView.mj_footer.hidden = NO;
                }
                //            刷新数据
                if (self.models.count)
                {
                    [self.tableView reloadData];
                }
                [self dismiss];
            }
            else
            {
                self.tableView.hidden  = YES;
                [self dismiss];
            }
        }
        else
        {
            [self dismiss];
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:responseDic[@"detail"]];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

#pragma mark - UIAlertView的代理方法
//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        if (alertView != self.alertView1)
        {
            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
            
            vc.successLoginBlock = ^
            {
                [self refreshData];
            };
        }
    }
    else
    {
        //确定取消共享
        NSString * url = @"record/cancelShared.do";
        
        NSDictionary *dict = @{@"recordId":@(self.cancelModel.id)};
        [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            if([responseObject[@"result"] isEqualToString:@"success"])
            {
                self.cancelModel.verified = NO;
                [self.tableView reloadRowsAtIndexPaths:@[self.cancelIndexPath] withRowAnimation:UITableViewRowAnimationNone];
            }
            else
            {
                [self showErrorInfoWithStatus:@"取消失败"];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           
            [self showErrorInfoWithStatus:@"网络错误"];
        }];
    }
}


-(void)loadMoreData
{
    NSDictionary *dict = @{@"page":@(self.pageIndex)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        
        if([responseDic[@"result"] isEqualToString:@"success"])
        {
            NSArray *detailArr = responseDic[@"detail"];
            
            if(!detailArr.count)
            {
                 [self.tableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
            
            for (NSDictionary  *obj in detailArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:obj];
                [self.models addObject:model];
                
                //                保存起来
                //                [NSKeyedArchiver archiveRootObject:self.models toFile:MRFilePath];
            }
            
            self.pageIndex++;
            //            刷新数据
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:responseDic[@"detail"]];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error)
        {
            [self.tableView.mj_footer endRefreshing];
            [self showErrorInfoWithStatus:@"网络错误"];
        }
        
    }];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WPMRTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    __weak typeof(self) weakSelf = self;
    cell.shareBtnDidClickBlock = ^(NSInteger index,BOOL isShared,WPMRModel *model){
        
        if (isShared)
        {
            self.cancelModel = model;
            self.cancelIndexPath = indexPath;
            
            //以共享点击
            UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"取消分享后您的病例将无法在阅读排名显示,不能再获得受益了哦" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            self.alertView1 = alertView1;
            [alertView1 show];
        }
        else
        {
            //共享点击
            WPShareToCommonCaseVC *vc = [WPShareToCommonCaseVC new];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
            vc.indexPath = indexPath;
            vc.delegate = self;
             vc.index = index;
            vc.model = model;
             [weakSelf presentViewController:nav animated:YES completion:nil];
        }
    };
    
    WPMRModel *model = self.models[indexPath.row];
    cell.model = model;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPNewEditeSpecificCasesVC *vc = [WPNewEditeSpecificCasesVC new];
//    vc.delegate = self;
    vc.model = self.models[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

//tableViewCell的左滑
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPMRModel *model = self.models[indexPath.item];
    NSString *url = @"record/deleteRecord.do";
    NSDictionary *dict = @{@"id":@(model.id)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = (NSDictionary *)responseObject;
        
        if ([dict[@"result"] isEqualToString:@"success"])
        {
            [self showSuccessInfoWithStatus:@"删除成功"];
            [self refreshData];
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else if ([responseObject[@"detail"] isEqualToString:@"forbidden"])
            {
//                收费病例禁止删除
                [self showErrorInfoWithStatus:@"删除失败，该病例在为您挣钱呢!"];
            }
            else
            {
                [self showErrorInfoWithStatus:@"删除失败"];
            }
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

-(void)refreshData
{
    //        执行下拉刷新操作
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        
        
        if([responseDic[@"result"] isEqualToString:@"success"])
        {
            NSArray *detailArr = responseDic[@"detail"];
            
            [self.models removeAllObjects];
            
            for (NSDictionary  *obj in detailArr)
            {
                WPMRModel *model = [WPMRModel yy_modelWithDictionary:obj];
                [self.models addObject:model];
            }
            
            self.pageIndex = 1;
            
            //不满一页就隐藏
            if(self.models.count == 0)
            {
                self.tableView.hidden = YES;
            }
            else
            {
                self.tableView.hidden = NO;
            }
            //刷新的时候不满一页就不显示
            if (self.models.count < 10)
            {
                self.tableView.mj_footer.hidden = YES;
            }
            else
            {
                self.tableView.mj_footer.hidden = NO;
            }
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        else
        {
            [self.tableView.mj_header endRefreshing];
            
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"刷新失败"];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error)
        {
            [self showErrorInfoWithStatus:@"网络错误"];
            [self.tableView.mj_header endRefreshing];
        }
    }];
}


- (IBAction)back
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    if (self.backBlock)
    {
        self.backBlock();
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (IBAction)add
{
//    注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveRefreshNotifaction) name:kRefreshNotifaction object:nil];
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    WPTabBarController *tab = (WPTabBarController *)delegate.window.rootViewController;
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WPUpdateDataVC" bundle:nil];
    WPUpdateDataVC *vc = [sb instantiateInitialViewController];
    
    UINavigationController *nvc = tab.childViewControllers[tab.selectedIndex];
    [nvc presentViewController:vc animated:YES completion:nil];
    
}

#pragma mark - WPShareToCommonCaseVCDelegate
-(void)WPShareToCommonCaseSuccessWith:(WPShareToCommonCaseVC *)vc with:(NSIndexPath *)indexPath
{
    //刷新某一行
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)receiveRefreshNotifaction
{
//    接收到通知
    [self refreshData];
}

-(void)dealloc
{
//    移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
//    NSLog(@"移除通知");
}

@end
